<template>
  <transition name="slide">
    <music-list :songs="songs" :title="title" :bgImage="bgImage" ></music-list>
  </transition>
</template>

<script>
import {mapGetters} from 'vuex' // 引用vuex提供的【取出数据】语法糖
import {getSingerDetail, getMusic} from 'api/singer'
import {ERR_OK} from 'api/config'
import {createSong} from 'common/js/song'
import MusicList from 'components/music-list/music-list'

export default {
  // data中维护一个数据 songs:[ ]
  data() {
    return {
      songs: []
    }
  },
  name: 'singer-detail.vue',
  computed: {
    // 在computed中通过mapGetters挂载singer属性
    title() {
      return this.singer.name
    },
    bgImage() {
      return this.singer.avatar
    },
    ...mapGetters([
      'singer'
    ])
  },
  // 在created()中打印出this.singer，查看vuex中数据的传递是否成功
  created() {
    this._getDetail()
    console.log(this.singer)
  },
  methods: {
    // 在methods中定义_getDetail()私有方法，通过调用getSingerDetail()返回promise对象，获取singer数据
    _getDetail() {
      // 当获取不到singer.id时，调用this.$route.push，使页面回退到singer路由
      if (!this.singer.id) {
        this.$router.push('/singer')
        return
      }
      getSingerDetail(this.singer.id).then((res) => {
        if (res.code === ERR_OK) {
          this.songs = this._normalizeSongs(res.data.list)
          console.log(this.songs)
        }
      })
    },
    _normalizeSongs(list) {
      let ret = [] // 返回值
      list.forEach((item) => {
        let {musicData} = item // 得到music对象
        // console.log(musicData)
        // createSong必传两个参数
        if (musicData.songid && musicData.albummid) {
          // console.log(getMusic(musicData.songmid))
          getMusic(musicData.songmid).then((res) => {
            // console.log(res)
            if (res.code === ERR_OK) {
              // console.log(res.data)
              const svkey = res.data.items
              const songVkey = svkey[0].vkey
              const newSong = createSong(musicData, songVkey)
              ret.push(newSong)
            }
          })
        }
      })
      // console.log(ret)
      return ret
    }
  },
  components: {
    MusicList
  }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"

    // 转场动画：从右向左滑动
  .slide-enter-active,.slide-leave-active
    transition all 0.3s

  .slide-enter,.slide-leave-to
    transform :translate3d(100%,0,0) // 100% 完全移动到屏幕右侧 动画开始后向左滑入
</style>
